package com.example.redis.controller;

import com.example.redis.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
@Slf4j
public class LoginController {

    @RequestMapping("login")
    @ResponseBody
    public String login(HttpServletResponse response, HttpServletRequest request) {
        //do something
        String token = UUID.randomUUID().toString();
        HttpSession session = request.getSession();
        session.setAttribute(token, new Student("yu", 12));
        Cookie cookie = new Cookie("userToken", token);
        cookie.setMaxAge(6000);
        response.addCookie(cookie);
        return "login success!";
    }

    @RequestMapping("checkLogin")
    @ResponseBody
    public String checkLogin(@CookieValue(required = false, value = "userToken") String userToken, HttpSession session) {
        if (!StringUtils.isEmpty(userToken)) {
            Student student = (Student) session.getAttribute(userToken);
            if (student != null) {
                System.out.println(student.getName());
                return "has logged in";
            }
        }
        return "not logged in";
    }

    @RequestMapping("logout")
    @ResponseBody
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("userToken".equals(cookie.getName())) {
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
        return "logout success!";
    }

    @RequestMapping("err")
    @ResponseBody
    public String err(HttpServletRequest request, HttpServletResponse response) {
        int i=1/0;
        return "logout success!";
    }

    @RequestMapping("/page")
    public String page(HttpServletRequest request, HttpServletResponse response) {
        System.out.println(111);
        return "404.html";
    }

    @RequestMapping("/pool")
    @ResponseBody
    @Async("asyncServiceExecutor")
    public void pool() {
        log.info("start executeAsync");

        System.out.println("异步线程要做的事情");
        System.out.println("可以在这里执行批量插入等耗时的事情");

        log.info("end executeAsync");
    }
}
